package com.healthcloud.controller.modules.instrument;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.healthcloud.annotation.SysLog;
import com.healthcloud.constants.InstrumentConsts;
import com.healthcloud.entity.*;
import com.healthcloud.service.BusInstrumentService;
import com.healthcloud.service.InstrumentService;
import com.healthcloud.service.QulitityService;
import com.healthcloud.utils.CommonMethod;
import com.healthcloud.utils.DateUtils;
import com.healthcloud.utils.ApiRes;
import com.healthcloud.utils.PageParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 仪器管理
 * Created by yucl on 2017/8/21.
 */
@ApiIgnore
@Controller
@RequestMapping(value = "/qulitity")
public class QulitityController {

    @Autowired
    private QulitityService qulitityService;

    @Autowired
    private InstrumentService instrumentService;

    @Autowired
    private CommonMethod commonMethod;

    @Autowired
    private BusInstrumentService instrService;


    private final String saveLinuxPath="/usr/local/tomcat/webapps/appdownloads/poct"; //linux保存路径

    private final String saveWinPath="D://appdownloads/poct";//windows保存路径



    @RequestMapping(value = "/toQulitity",method= RequestMethod.GET)
    public String toSearchInstrumentInstall(){
        return "newframe/qulitity";
    }


    @RequestMapping(value = "/search")
    public @ResponseBody
    MsgVo searchInstrumentInstall(QulitityEntity bean, Model model, @ModelAttribute("pageParam")PageParam pageParam){
        List<QulitityEntity> list = qulitityService.search(bean, pageParam);
        int count = qulitityService.count(bean);

        return new MsgVo(list,count,count,pageParam.getsEcho());
    }

    @RequestMapping(value = "/toKbList",method=RequestMethod.GET)
    public String toListKb(String id, Model model){
        model.addAttribute("machineId", id);
        return "newframe/kblist";
    }

    @RequestMapping(value = "/searchKb")
    @ResponseBody
    public Map<String, Object> searchKb(CheckKBEntity bean, Model model,
                                        @ModelAttribute("pageParam") PageParam pageParam) {
        List<CheckKBEntity> list = qulitityService.searchKB(bean, pageParam);
        int count = qulitityService.countKB(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequestMapping(value = "/toKb",method=RequestMethod.GET)
    public String toUpdateKb(String id, Model model){
        CheckKBEntity bean = qulitityService.searchKBById(Integer.parseInt(id));
        model.addAttribute("entity", bean);
        return "newframe/update_kb";
    }

    @RequestMapping(value = "/updateKb")
    public @ResponseBody
    ApiRes updateKB(CheckKBEntity bean) {
        qulitityService.updateKB(bean);
        return new ApiRes(true,null,null,null);
    }

    @RequestMapping(value = "/toAddKb",method=RequestMethod.GET)
    public String toAddKb(String id, Model model){
        model.addAttribute("machineId", id);
        return "newframe/add_kb";
    }

    @RequestMapping(value = "/addKb")
    @ResponseBody
    public ApiRes addKB(CheckKBEntity bean) {
        qulitityService.addKB(bean);
        return new ApiRes(true,null,null,null);
    }

    /**
     * 删除 kb
     */
    @SysLog("删除KB")
    @RequestMapping("/deleteKb")
    @ResponseBody
    public ApiRes delete(Integer[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            return ApiRes.ERROR;
        }
        qulitityService.deleteBatchByIds(ids);
        return ApiRes.SUCCESS;
    }


    @RequestMapping(value = "/toRecord",method=RequestMethod.GET)
    public String toRecord(String machineId,Model model){
        model.addAttribute("machineId", machineId);
        return "newframe/record";
    }

    @RequestMapping(value = "/record")
    public @ResponseBody
    Map<String, Object>  searchRecord(TestDataEntity bean, Model model, @ModelAttribute("pageParam")PageParam pageParam){
        List<TestDataEntity> list = qulitityService.record(bean, pageParam);
        int count = qulitityService.countRecord(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequestMapping(value = "/toQuadata",method=RequestMethod.GET)
    public String toQuadata(String machineId,Model model){
        model.addAttribute("machineId", machineId);
        return "newframe/quadata";
    }

    @RequestMapping(value = "/quadata")
    public @ResponseBody
    Map<String, Object>  searchQuadata(QualityEntity bean, Model model, @ModelAttribute("pageParam")PageParam pageParam){
        List<QualityEntity> list = qulitityService.quadata(bean, pageParam);
        int count = qulitityService.countQuadata(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequestMapping(value = "/toRemote",method=RequestMethod.GET)
    public String toRemoteMgr(){
        return "newframe/remotemgr";
    }


    @RequestMapping(value = "/toDevice",method=RequestMethod.GET)
    public String toDeviceMgr(){
        return "newframe/devicemgr";
    }


    @RequestMapping(value = "/searchDevice")
    public @ResponseBody
    Map<String, Object>  searchDevice(InstrumentInfo bean,Model model, @ModelAttribute("pageParam")PageParam pageParam){
        List<InstrumentInfo> list = qulitityService.searchDevice(bean, pageParam);
        int count = qulitityService.countDevice(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @RequestMapping(value = "/toUpdateDevice",method=RequestMethod.GET)
    public String toUpdateDevice(String id,String method, Model model){
        InstrumentInfo entity = null;
        if("2".equals(method)){
            entity = qulitityService.searchDeviceById(Integer.parseInt(id));
        }
        model.addAttribute("entity", entity);
        return "newframe/update_device";
    }

    @RequestMapping(value = "/updateDevice")
    public @ResponseBody
    ApiRes updateDevice(InstrumentInfo bean) {
        if(bean.getId() == null){
            bean.setIsDel(false);
            qulitityService.createDevice(bean);
        }else{
            qulitityService.updateDevice(bean);
        }
        return new ApiRes(true,null,null,null);
    }

    @RequestMapping(value = "/deleteDevice")
    public @ResponseBody
    ApiRes deleteDevice(String[] ids) {
        int[] idArr = new int[ids.length];
        // TODO 参数检测
        for (int i=0; i<ids.length; i++){
            Integer l = null;
            try {
                l = Integer.valueOf(ids[i]);
                idArr[i] = l;
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }
        qulitityService.deletes(idArr);
        return new ApiRes(true,null,null,null);
    }

    @RequestMapping(value = "/toDeviceRepair",method=RequestMethod.GET)
    public String toDeviceRepair(String id,String SN,Model model){
        model.addAttribute("instrumentId", id);
        InstrumentInstallEntity entity = qulitityService.searchInstallById(Integer.parseInt(id));
        model.addAttribute("SN",entity.getMkMedicalInstrumenId());
        return "newframe/devicerepair";
    }



    @RequestMapping(value = "/toInstall",method=RequestMethod.GET)
    public String toInstall(){
        return "newframe/deviceinstall";
    }

    @RequestMapping(value = "/searchInstall")
    public @ResponseBody
    Map<String, Object>  searchInstall(InstrumentInstallEntity bean,Model model, @ModelAttribute("pageParam")PageParam pageParam){
        List<InstrumentInstallEntity> list = qulitityService.searchInstall(bean, pageParam);
        int count = qulitityService.countInstall(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", list);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }
    @RequestMapping(value = "/toUpdateInstall",method=RequestMethod.GET)
    public String toUpdateInstall(String id,String method, Model model){
        InstrumentInstallEntity entity = null;
        //2,修改，3，装机
        if("2".equals(method) || "3".equals(method)){
            entity = qulitityService.searchInstallById(Integer.parseInt(id));
            entity.setMt(method);
        }
        model.addAttribute("entity", entity);

        if(entity != null && entity.getInstallTime() != null){

            String _installTime = new DateUtils().format(entity.getInstallTime());
            model.addAttribute("installTime",_installTime);
        }

        InstrumentEntity instrumentEntity = new InstrumentEntity();
        instrumentEntity.setType(2);
        List<InstrumentEntity> instrumentList = instrumentService.findByEntityAll(instrumentEntity);
        model.addAttribute("instrumentList",instrumentList);
        Hospital hospital = new Hospital(true);
        hospital.setIsDel(false);
        /*List<Hospital> hospitalList = hospitalService.findByEntityAll(hospital);
        model.addAttribute("hospitalList",hospitalList);*/
        return "newframe/update_deviceinstall";
    }

    @RequestMapping(value = "/updateInstall")
    public @ResponseBody
    ApiRes updateInstall(InstrumentInstallEntity bean) {

        InstrumentInfo instrumentInfo = qulitityService.searchDeviceById(bean.getInstrumentId());
        BusInstrumentEntity instrumentEntity = new BusInstrumentEntity();
        instrumentEntity.setInstrumentSN(bean.getMkMedicalInstrumenId());
        instrumentEntity.setInstrumentType(instrumentInfo.getInstrumentName());

        if(bean.getId() == null){
            //新增前验证SN是否存在
            if(qulitityService.searchInstallByEntity(bean).size() > 0){
                return new ApiRes(false,null,null,"此仪器SN号已安装！");
            }
            //设备新增，未投放

            instrumentEntity.setInstrumentStatus(InstrumentConsts.INSTRUMENT_STATUS_UNINSTALL);
            instrService.createInstr(instrumentEntity);

            qulitityService.createInstall(bean);
        }else if("2".equals(bean.getMt())){
            InstrumentInstallEntity oldEntity = qulitityService.searchInstallById(bean.getId());
            if (!bean.getMkMedicalInstrumenId().equals(
                    oldEntity.getMkMedicalInstrumenId())) {
                if(qulitityService.searchInstallByEntity(bean).size() > 0){
                    return new ApiRes(false,null,null,"此仪器SN号已安装！");
                }
            }

            //设备修改，未投放
            instrumentEntity.setInstrumentStatus(InstrumentConsts.INSTRUMENT_STATUS_UNINSTALL);
            instrService.updateInstr(instrumentEntity);

            qulitityService.updateInstall(bean);
        }else if("3".equals(bean.getMt())){

            //设备修改，未投放

            instrumentEntity.setInstrumentStatus(InstrumentConsts.INSTRUMENT_STATUS_INSTALL);
            instrService.updateInstr(instrumentEntity);
            qulitityService.infoInstall(bean);
        }
        return new ApiRes(true,null,null,null);
    }

    @RequestMapping(value = "/deleteInstall")
    public @ResponseBody
    ApiRes deleteInstall(String[] ids) {
        int[] idArr = new int[ids.length];
        // TODO 参数检测
        for (int i=0; i<ids.length; i++){
            Integer l = null;
            try {
                l = Integer.valueOf(ids[i]);
                idArr[i] = l;
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }
        qulitityService.deletesInstall(idArr);
        return new ApiRes(true,null,null,null);
    }

    @RequestMapping(value = "/unbundlingInstall")
    public @ResponseBody
    ApiRes unbundlingInstall(String[] ids) {
        List<Integer> list = new ArrayList<Integer>();
        // TODO 参数检测
        for (int i=0; i<ids.length; i++){
            Integer l = null;
            try {
                l = Integer.valueOf(ids[i]);
                list.add(l);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }
        qulitityService.unbundlingInstall(list);
        return new ApiRes(true,null,null,null);
    }

}
